/**
 * File    : Authentication.java
 * Created : 2008-9-9
 * By      : LuHuiguo
 */
package com.luhuiguo.tapestry5.security.components;

import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Parameter;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;

/**
 * @author LuHuiguo
 * @version $Id: Authentication.java 2 2008-09-29 04:06:22Z LuHuiguo $
 * 
 */
public class Authentication {

	@Parameter(required = true, defaultPrefix = "literal")
	private String operation;

	@AfterRender
	void afterRender(MarkupWriter writer) {

		Object value = null;
		if (operation != null) {

			if ((SecurityContextHolder.getContext() == null)
					|| !(SecurityContextHolder.getContext() instanceof SecurityContext)
					|| (SecurityContextHolder.getContext().getAuthentication() == null)) {
				return;
			}

			org.springframework.security.Authentication auth = SecurityContextHolder
					.getContext().getAuthentication();

			if (auth.getPrincipal() == null) {
				return;
			} else {
				try {
					BeanWrapperImpl wrapper = new BeanWrapperImpl(auth);
					value = wrapper.getPropertyValue(operation);

				} catch (BeansException e) {
					e.printStackTrace();

					writer.writeRaw("[" + operation.toUpperCase() + "]");
				}
			}

			if (value != null) {
				writer.writeRaw(value.toString());
			}
		}
	}

}
